from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient
from todo import router as todo_router


def create_app():
    app = FastAPI()

    @app.on_event('startup')
    async def db_startup():
        # 可以使用两种方式连接mongodb数据库
        # app.state.mongodb_client = AsyncIOMotorClient('mongodb://127.0.0.1:27017/')
        # app.state.db = app.state.mongodb_client['testdb']

        app.state.mongodb_client = AsyncIOMotorClient('mongodb://127.0.0.1:27017/testdb')
        app.state.db = app.state.mongodb_client.get_default_database()

    @app.on_event('shutdown')
    async def db_shutdown():
        app.state.mongodb_client.close()

    return app


app = create_app()
app.include_router(todo_router, prefix='/api', tags=['Todo app'])

if __name__ == '__main__':
    import uvicorn

    uvicorn.run('run:app', debug=True, reload=True)
